<template>
  <view class="container">
    <!-- 动态添加图片 -->
		<view class="addimage">
		  <view>图片上传</view>
		  <view style="margin-top: 20rpx;">
			<view class="img" v-for="(item, i) in product.images" :key="i" @click="viewImage(i)">
			  <image style="width: 100%; height: 100%;" :src="item.uri"></image>
			  <view @click.stop="delImg(i)" style="display: inline;">
				<uni-icons type="closeempty" class="close" size="20"></uni-icons>
			  </view>
			  <!-- 显示主图标识 -->
			  <view v-if="i === 0" style="position: absolute; top: 5rpx; left: 5rpx; background: rgba(255, 0, 0, 0.7); color: #fff; padding: 2rpx 5rpx; border-radius: 5rpx;">
				主图
			  </view>
			</view>
			<view class="camera" @tap="chooseImage">
			  <uni-icons type="camera" size="40"></uni-icons>
			</view>
		  </view>
		</view>
		
    <uni-form ref="form" @submit="submitProduct">
      <!-- 基本商品信息 -->
	  <view  class="section">
      <uni-section title="品类" type="line">
        <uni-data-select
          v-model="product.categoryId"
          :localdata="cateList"
          @change="handleCateChange"
          :clear="false"
          :placeholder="'请选择分类'"
        ></uni-data-select>
      </uni-section>
	</view>
      <uni-forms-item label="名称" required>
        <uni-easyinput v-model="product.productName" :inputBorder="false" placeholder="请输入商品名称" />
      </uni-forms-item>

      <uni-forms-item label="价格" required>
        <uni-easyinput v-model.number="product.price" :inputBorder="false" placeholder="请输入商品价格" />
      </uni-forms-item>

      <uni-forms-item label="发货地" required>
        <uni-easyinput v-model="product.originLocation" :inputBorder="false" placeholder="请输入发货地" />
      </uni-forms-item>

      <uni-forms-item label="单位" >
        <uni-easyinput v-model="product.unit" :inputBorder="false" placeholder="请输入商品单位" />
      </uni-forms-item>

      <uni-forms-item label="产品类型" >
        <uni-easyinput v-model="product.productType" :inputBorder="false" placeholder="请输入产品类型" />
      </uni-forms-item>

      <uni-forms-item label="商品等级">
        <uni-easyinput v-model="product.grade" :inputBorder="false" placeholder="请输入商品等级" />
      </uni-forms-item>

      <uni-forms-item label="产品大小">
        <uni-easyinput v-model="product.size" :inputBorder="false" placeholder="请输入产品大小" />
      </uni-forms-item>

      <uni-forms-item label="单份重量" >
        <uni-easyinput v-model.number="product.unitWeight" :inputBorder="false" placeholder="请输入单份重量" />
      </uni-forms-item>

      <uni-forms-item label="产品介绍" required>
        <uni-easyinput
          v-model="product.description"
          :inputBorder="false"
          type="textarea"
          placeholder="请输入产品介绍"
        />
      </uni-forms-item>

      <!-- 动态添加 SKU -->
      <view class="section">
        <label>商品规格:</label>
        <view v-for="(sku, index) in product.skus" :key="index" class="sku-group">
          <input v-model="sku.skuName" placeholder="规格名称" />
          <input v-model.number="sku.price" placeholder="规格价格" type="number" />
          <input v-model.number="sku.stock" placeholder="规格库存" type="number" />
          <input v-model="sku.unit" placeholder="单位" />
          <input v-model.number="sku.minPurchase" placeholder="最小购买量" type="number" />
          <input v-model.number="sku.maxPurchase" placeholder="最大购买量" type="number" />
          <button @click.prevent="removeSku(index)">删除</button>
        </view>
        <button @click.prevent="addSku" class="addsku-button">添加商品规格</button>
      </view>

      <!-- 提交按钮 -->
      <view class="button-group">
        <button  type="primary" @click="submitProduct">发布商品</button>
      </view>
    </uni-form>
  </view>
</template>

<script>
import { getCateList, createPruduct } from "@/api/home/goods.js"; // API 接口

export default {
  data() {
    return {
      product: {
        categoryId: null,
        userId: null,
        productName: "",
        price: null,
        unit: null,
        status: "",
        images: [], // 商品图片
        originLocation: "",
        productType: "",
        grade: "",
        size: "",
        unitWeight: null,
        description: "",
        skus: [], // 商品 SKU
      },
      cateList: [], // 分类数据
    };
  },
  onLoad() {
    this.getCateList();
    this.getUserInfo();
  },
  methods: {
    // 获取用户信息
    async getUserInfo() {
      try {
        const userInfo = this.$store.state.user; // 从 Vuex 中获取用户信息
        this.product.userId = userInfo.userId;
      } catch (error) {
        console.error("获取用户信息失败:", error);
        uni.showToast({ title: "获取用户信息失败", icon: "none" });
      }
    },
    // 获取分类列表
    async getCateList() {
      try {
        const data = await getCateList(); // 获取分类列表接口
        this.cateList = data.map((item) => ({
          text: item.categoryName,
          value: item.categoryId,
        }));
      } catch (error) {
        console.error("获取品类数据失败:", error);
        uni.showToast({ title: "获取分类数据失败", icon: "none" });
      }
    },
    handleCateChange(value) {
      this.product.categoryId = value;
    },

    // 动态添加 SKU
    addSku() {
      this.product.skus.push({
        skuName: "",
        price: null,
        stock: null,
        unit: "",
        minPurchase: null,
        maxPurchase: null,
      });
    },
    removeSku(index) {
      this.product.skus.splice(index, 1);
    },

    // 图片上传
    async uploadImage(filePath) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: 'http://localhost:8080/shop/upload', 
          filePath: filePath,
          name: 'file',
          success: (uploadResult) => {
            try {
              const res = JSON.parse(uploadResult.data);
              if (res.url) {
                console.log(res.url); // 正常值
                resolve(res.url); // 成功返回 URL
              } else {
                uni.showToast({ title: '图片上传失败', icon: 'none' });
                reject(new Error('图片上传失败，未返回 URL'));
              }
            } catch (error) {
              console.error('JSON 解析失败:', error);
              uni.showToast({ title: '图片上传失败', icon: 'none' });
              reject(error);
            }
          },
          fail: (err) => {
            console.error('图片上传失败:', err);
            uni.showToast({ title: '图片上传失败', icon: 'none' });
            reject(err);
          },
        });
      });
    },

    // 选择图片
    async chooseImage() {
      const _this = this;
      uni.chooseImage({
        count: 9 - _this.product.images.length, // 限制上传的图片数量
        sizeType: ["compressed"],
        sourceType: ["album", "camera"],
        success: function (res) {
          const tempFilePaths = res.tempFilePaths.map((filePath, index) => ({
            uri: filePath,
            isUploaded: false,
            isPrimary: _this.product.images.length === 0 && index === 0, // 如果是第一张图，标记为主图
          }));
          _this.product.images.push(...tempFilePaths);

          // 确保第一张图为主图，更新其他图片的 isPrimary
          _this.updatePrimaryImage();
        },
        fail: function (err) {
          uni.showToast({ title: "选择图片失败", icon: "none" });
          console.error("选择图片失败：", err);
        },
      });
    },

    // 删除图片
    delImg(index) {
      this.product.images.splice(index, 1);

      // 确保第一张图为主图，更新其他图片的 isPrimary
      this.updatePrimaryImage();
    },

    updatePrimaryImage() {
      this.product.images.forEach((image, index) => {
        image.isPrimary = index === 0;
      });
    },

    // 查看大图
    viewImage(index) {
      const urls = this.product.images.map((img) => img.uri);
      uni.previewImage({
        current: urls[index],
        urls,
      });
    },

    // 提交商品
    async submitProduct() {
      try {
        // 校验必填字段
        if (!this.product.originLocation || !this.product.description || !this.product.productName || !this.product.price || !this.product.categoryId) {
          uni.showToast({ title: "请完善必填信息", icon: "none" });
          return;
        }

        // 校验价格是否为数字且大于 0
        if (isNaN(this.product.price) || this.product.price <= 0) {
          uni.showToast({ title: "请输入有效的商品价格", icon: "none" });
          return;
        }

        // 校验图片至少一张
        if (this.product.images.length === 0) {
          uni.showToast({ title: "请至少上传一张图片", icon: "none" });
          return;
        }

        // 上传图片并更新 URL
        for (const image of this.product.images) {
          if (!image.isUploaded) {
            const uploadedUrl = await this.uploadImage(image.uri);
			console.log(uploadedUrl)
            if (uploadedUrl) {
              image.uri = uploadedUrl;
              image.isUploaded = true; // 标记已上传
            } else {
              uni.showToast({ title: "图片上传失败", icon: "none" });
              return; // 停止提交
            }
          }
        }

        // 提交商品信息
        const productData = {
          ...this.product,
          images: this.product.images.map((img) => ({
            imageUrl: img.uri,
            isPrimary: img.isPrimary, // 提交 isPrimary
          })),
        };

        await createPruduct(productData);

        uni.showToast({ title: "商品发布成功", icon: "success" });
		// 销毁当前页面并跳转
		uni.redirectTo({
		  url: `/pages/publish/index/index`, // 确保 URL 使用正确参数
		});
      } catch (error) {
        console.error("提交失败:", error);
        uni.showToast({ title: "商品发布失败", icon: "error" });
      }
    },
  },
};
</script>

<style lang="scss">
	
.img {
		position: relative;
		display: inline-block;
		width: 166rpx;
		height: 166rpx;
		vertical-align: top;
		margin-right: 10rpx;
		margin-bottom: 10rpx;
	}
.close {
	position: absolute;
	right: 0;
	background-color: rgba(0, 0, 0, .4);
	color: #fff;
}
.camera {
	display: inline-block;
	width: 166rpx;
	height: 166rpx;
	text-align: center;
	line-height: 166rpx;
	font-size: 46rpx;
	border: 1rpx dotted #8C9697;
	color: #8C9697;
	margin-bottom: 10rpx;
}
.container {
  padding: 20px;
}

.sku-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
  margin-bottom: 20rpx;
  padding: 10rpx;
  background: #f9f9f9;
  border-radius: 5rpx;
}

.sku-group input {
  flex: 1 1 calc(50% - 10rpx); /* 每个输入框占一半宽度，留出间距 */
  box-sizing: border-box;
  padding: 10rpx;
  border: 1rpx solid #ccc;
  border-radius: 5rpx;
}

.sku-group input {
  flex: 1 1 calc(50% - 10rpx); /* 每个输入框适配宽度 */
  height: 60rpx; /* 调整输入框高度 */
  padding: 10rpx; /* 添加内边距以增加触控区域 */
  border: 1rpx solid #ccc; /* 边框样式 */
  border-radius: 8rpx; /* 添加圆角 */
  font-size: 28rpx; /* 字体大小 */
  box-sizing: border-box; /* 确保内边距不会影响宽度计算 */
}

.sku-group input[type="number"] {
  height: 60rpx; /* 确保数字输入框高度一致 */
}

.sku-group {
  margin-bottom: 20rpx; /* 每组 SKU 的间距 */
}

.sku-group button {

  flex: 1 1 80%;
  
  background: #e74c3c;
  color: #fff;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  text-align: center;
}

.addsku-button{
	background-color: #3498db;
	 border-radius: 10px;
}

/* 表单通用样式 */
.uni-forms-item {
  margin-bottom: 20rpx;
}
.section{
	margin-top: 20px;
	margin-bottom: 20px;
}


button[type="primary"] {
  background: #00aa00;
  color: #fff;
  padding: 15rpx 30rpx;
  border: none;
  border-radius: 10px;
  font-size: 16px;
  cursor: pointer;
}

button[type="primary"]:hover {
  background: #2980b9;
}
</style>
